package com.zone.api.di

import android.content.Context
import android.os.Build
import android.os.Environment
import android.util.Log
import androidx.annotation.RequiresApi
import com.google.gson.reflect.TypeToken
import com.zone.api.model.ApiResponse
import com.zone.api.model.LoginResBean
import com.zone.core.CoreApplication
import com.zone.core.ext.assetsOpen
import com.zone.core.ext.fromJson
import com.zone.core.ext.toJson
import okhttp3.Interceptor
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.io.File
import java.io.IOException
import java.io.OutputStreamWriter


/**
 *Author: last
 *Time: 2024/1/20
 *Description: 接口拦截
 */

class ApiInterceptor : Interceptor {

    /**
     *  adb 移动复制接口数据命令
     *  adb pull /storage/emulated/0/Android/data/com.zone.module_api/files/Download C:\Users\last\Desktop
     */

    companion object {
        var context: Context = CoreApplication.coreApp
        val interceptorApi = HashMap<String, Any>()

        fun addApiDataList() {
            "apiData/apiDataList.json".assetsOpen().let {
                val bean = it.fromJson<ApiResponse<LoginResBean>>(object :
                    TypeToken<ApiResponse<LoginResBean>>() {}.type)
                interceptorApi["apiData/apiDataList.json"] = bean
            }
            "apiData/apiDataList.json".assetsOpen().let {
                val bean = it.fromJson<ApiResponse<LoginResBean>>(object :
                    TypeToken<ApiResponse<LoginResBean>>() {}.type)
                interceptorApi["apiData/apiDataList.json"] = bean
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        var response: Response?
        interceptorApi.forEach { (t, u) ->
            if (request.url.encodedPath.contains(t)) {
                val path = pathChange(request.url.encodedPath)
                saveApiData(path, u)
                response = Response.Builder()
                    .request(request)
                    .protocol(Protocol.HTTP_1_1)
                    .code(200)
                    .message("OK")
                    .body(
                        u.toJson().toResponseBody()
                    )
                    .addHeader("Content-Type", "application/json")
                    .build()
                return response!!
            }
        }

        chain.proceed(request).let {
            Log.d("TAG", "intercept: ")
            it.body?.let {
                val path = pathChange(request.url.encodedPath)
                saveApiData(path, it)
            }
            return it
        }
    }

    private fun pathChange(path: String): String {
        return path.replace("/", "_") + ".json"
    }

    private fun saveApiData(fileName: String, data: Any) {
        writeDataToExternalStorage(fileName, data.toJson())
    }

    private fun writeDataToExternalStorage(
        fileName: String,
        content: String
    ) {
        val file = File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), fileName)
        try {
            if (!file.exists()) {
                file.createNewFile()
            }
            val outputStreamWriter = OutputStreamWriter(file.outputStream())
            outputStreamWriter.write(content)
            outputStreamWriter.flush()
            outputStreamWriter.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}
